package com.zoro.dyformservice.support.filter.request;

import com.zoro.dyformservice.utils.JsonUtil;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author zhaoxingwu
 */
public final class MultipleReadableServletRequest extends HttpServletRequestWrapper {

    private final String jsonBody;

    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request original request
     * @throws IllegalArgumentException if the request is null
     */
    public MultipleReadableServletRequest(HttpServletRequest request) throws IOException {
        super(request);
        this.jsonBody = JsonUtil.readJson(request.getInputStream()).toString();
    }

    public MultipleReadableServletRequest(HttpServletRequest request, String defaultBody) {
        super(request);
        this.jsonBody = defaultBody;
    }

    @Override
    public ServletInputStream getInputStream() {
        return new MultipleReadableServletInputStream();
    }

    private class MultipleReadableServletInputStream extends ServletInputStream {
        private int position = 0;
        private final byte[] bytes;


        public MultipleReadableServletInputStream() {
            bytes = jsonBody.getBytes(StandardCharsets.UTF_8);
        }

        @Override
        public boolean isFinished() {
            return position == bytes.length;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener readListener) {

        }

        @Override
        public int read() {
            if (position == bytes.length) {
                return -1;
            }
            return bytes[position++];
        }
    }
}
